package mamikeji.liaowa.ui.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.squareup.okhttp.Request;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import mamikeji.liaowa.R;
import mamikeji.liaowa.application.MyApplication;
import mamikeji.liaowa.bean.UserBean;
import mamikeji.liaowa.http_api.ForHttp;
import mamikeji.liaowa.http_api.HttpApi;
import mamikeji.liaowa.http_api.HttpKey;
import mamikeji.liaowa.utils.ForContents;
import mamikeji.liaowa.utils.ForLog;
import mamikeji.liaowa.utils.ForPreference;
import mamikeji.liaowa.utils.ForToast;
import mamikeji.liaowa.utils.MaxTextLength;
import mamikeji.liaowa.widget.ForDialog;
import mamikeji.liaowa.widget.VerifyCode;

/**
 * Created by 廉冲-android开发 on 2017/5/5.
 */
public class LoginActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "LoginActivity";
    TextView editText_login_userphone, tv_login_authcode;
    EditText editText_login_code, editText_login_dig_code;
    RelativeLayout relativeLayout_login;
    private LinearLayout linearLayout_code_voice;
    private String user_phone, phone_code;

    private ForDialog forDialog;
    private VerifyCode verifyCode_login;

    private TextView textView_login;
    private RelativeLayout relativeLayout_login_dig_code_query;

    private static final int MSG_SET_ALIAS = 1002;

    /**
     * 短信验证码间隔时间
     */
    private int second = ForContents.GET_SMS_CODE;
    //每隔一秒修改按钮状态
    private Handler hander = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {
                //获取验证码
                case 0:
                    relativeLayout_login.setBackgroundResource(R.drawable.shape_login_btn_sel_bg);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        relativeLayout_login.setElevation(10);
                    }
                    //这样写的目的是减小运算量,只需要一次设置就够了
                    if (tv_login_authcode.isEnabled()) {
                        tv_login_authcode.setEnabled(false);
                        tv_login_authcode.setTextColor(R.color.color_C9C9C9);
                    }
                    tv_login_authcode.setText(getString(R.string.login_code_left) + second-- + getString(R.string.login_code_right));

                    if (0 > second) {
                        second = ForContents.GET_SMS_CODE;
                        tv_login_authcode.setTextColor(Color.parseColor("#333333"));
                        tv_login_authcode.setText(getText(R.string.login_code));
                        tv_login_authcode.setEnabled(true);
                        textView_login.setText(R.string.login_denglu);
                    } else {
                        hander.sendMessageDelayed(Message.obtain(), 1000);
                    }
                    break;
                //自动读取验证码
                case 1:
                    String codeMsg = msg.getData().getString("messagecode");
                    ForLog.i("得到的code", codeMsg);
                    editText_login_code.setText(codeMsg);
                    break;
            }

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        getBase();
        setTitleLeftBtn();
        setTitleName(R.string.login_name);
        init();
    }

    /**
     * 加载布局控件
     */
    private void init() {
        textView_login = (TextView) findViewById(R.id.textView_login);
        editText_login_userphone = (EditText) findViewById(R.id.editText_login_userphone);
        editText_login_code = (EditText) findViewById(R.id.editText_login_code);
        tv_login_authcode = (TextView) findViewById(R.id.tv_login_authcode);
        relativeLayout_login = (RelativeLayout) findViewById(R.id.relativeLayout_login);
        linearLayout_code_voice = (LinearLayout) findViewById(R.id.linearLayout_code_voice);

        getDigLog();

        relativeLayout_login.setOnClickListener(null);
        tv_login_authcode.setOnClickListener(this);

        editText_login_userphone.addTextChangedListener(watcher);

        relativeLayout_login.setBackgroundResource(R.drawable.shape_login_btn_bg);

        InputFilter[] filters = new InputFilter[]{new MaxTextLength(6)};
        editText_login_code.setFilters(filters);
    }

    private TextWatcher watcher = new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // TODO Auto-generated method stub
            if (editText_login_userphone.getText().length() == 11) {
                tv_login_authcode.setTextColor(Color.parseColor("#333333"));
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub

        }
    };

    @Override
    public void onClick(View view) {
        user_phone = editText_login_userphone.getText().toString();
        phone_code = editText_login_code.getText().toString();
        switch (view.getId()) {
            case R.id.tv_login_authcode:
                if (TextUtils.isEmpty(user_phone)) {
                    ForToast.showToast(R.string.login_error_userphone);
                    return;
                }
                if (!isMobileNO(user_phone)) {
                    ForToast.showToast(R.string.login_error_phone_format);
                    return;
                }
                forDialog.show();
                break;
            case R.id.relativeLayout_login:
                if (!isMobileNO(user_phone)) {
                    ForToast.showToast(R.string.login_error_userphone);
                    return;
                }
                if (TextUtils.isEmpty(phone_code)) {
                    ForToast.showToast(R.string.login_error_phonecode);
                    return;
                }
                //登陆
                userLogin(user_phone, phone_code);
                break;
        }
    }

    private void getDigLog() {
        forDialog = new ForDialog(this, R.layout.diglog_codeimg) {
            @Override
            public void init() {
                relativeLayout_login_dig_code_query = (RelativeLayout) findViewById(R.id.relativeLayout_login_dig_code_query);
                editText_login_dig_code = (EditText) findViewById(R.id.editText_login_dig_code);
                verifyCode_login = (VerifyCode) findViewById(R.id.verifyCode_login);

                relativeLayout_login_dig_code_query.setOnClickListener(this);

                editText_login_dig_code.setText("");
                verifyCode_login.findFocus();
            }

            @Override
            public void onClick(View view) {
                switch (view.getId()) {
                    case R.id.relativeLayout_login_dig_code_query:
                        if (TextUtils.isEmpty(editText_login_dig_code.getText().toString())) {
                            ForToast.showToast(R.string.login_dig_title);
                            return;
                        }
                        if (!verifyCode_login.isEquals(editText_login_dig_code.getText().toString())) {
                            ForToast.showToast(R.string.login_dig_code_error);
                            verifyCode_login.refresh();
                            return;
                        }
                        editText_login_dig_code.setText("");
                        verifyCode_login.findFocus();
                        forDialog.hide();
                        requestAuthCode();
                        break;
                }
            }
        };
    }

    /**
     * 验证手机格式
     */
    public static boolean isMobileNO(String mobiles) {
    /*
    移动：134、135、136、137、138、139、150、151、157(TD)、158、159、187、188
    联通：130、131、132、152、155、156、185、186
    电信：133、153、180、189、（1349卫通）
    总结起来就是第一位必定为1，第二位必定为3或5或8，其他位置的可以为0-9
    */
        String telRegex = "[1][3578]\\d{9}";//"[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        if (TextUtils.isEmpty(mobiles)) {
            return false;
        } else {
            return mobiles.matches(telRegex);
        }
    }

    /**
     * 先判断手机号不为空，获取短信验证码
     */
    public void requestAuthCode() {
        //参数集合
        Map<String, String> formMap = new HashMap<String, String>();
        formMap.put(HttpKey.LOGIN_PHONE, user_phone);
        formMap.put(HttpKey.LOGIN_SOURCE, HttpKey.ANDROID);
        ForHttp.setMsg(HttpApi.ROOT_PATH + HttpApi.LOGIN_PHONECODE, formMap, new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                ForLog.i(TAG, e.getMessage().toString());
                ForToast.showToast(R.string.intent_error);
                Message msg = new Message();
                msg.what = 0;
                hander.sendMessage(msg);
            }

            @Override
            public void onResponse(String response) {
                ForLog.i(TAG, response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString(HttpKey.STATUS);
                    if ("200".equals(status)) {
                        Message msg = new Message();
                        msg.what = 0;
                        hander.sendMessage(msg);

                        relativeLayout_login.setOnClickListener(LoginActivity.this);
                    } else {
                        Message msg = new Message();
                        msg.what = 0;
                        hander.sendMessage(msg);
                    }
                    ForToast.showToast(jsonObject.getString(HttpKey.MESSAGE));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * @param name:用户名
     * @param pwd：密码
     */
    public void userLogin(final String name, String pwd) {
        showLoading();
        Map<String, String> formMap = new HashMap<>();
        formMap.put(HttpKey.LOGIN_PHONE, name);
        formMap.put(HttpKey.LOGIN_CODE, pwd);
        formMap.put(HttpKey.LOGIN_DeviceIdentifier, "");
        formMap.put(HttpKey.LOGIN_group_id, ForContents.GET_2);
        ForHttp.setMsg(HttpApi.ROOT_PATH + HttpApi.LOGIN_lOGIN, formMap, new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {

                if (ForLog.isLogCatEnabled) ForLog.i(TAG, e.getMessage().toString());

                ForToast.showToast(R.string.intent_error);
                hideLoading();
            }

            @Override
            public void onResponse(String response) {
                if (ForLog.isLogCatEnabled) ForLog.i(TAG, response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString(HttpKey.STATUS);
                    if ("200".equals(status)) {
                        UserBean userBean = new Gson().fromJson(response, UserBean.class);
                        //储存登陆信息，token
                        ForPreference.putString(ForContents.USER_ID, userBean.getUser().getId() + "");
                        ForPreference.putString(ForContents.USER_CODE, userBean.getUser().getUsercode());
                        ForPreference.putString(ForContents.USER_HEADERURL, userBean.getUser().getAvatar());
                        ForPreference.putInt(ForContents.USER_COUNT, userBean.getUser().getCount());
                        ForPreference.putString(ForContents.USER_NAME, userBean.getUser().getNick_name());
                        ForPreference.putString(ForContents.USER_SEX, userBean.getUser().getSex());
                        ForPreference.putString(ForContents.USER_BIRTHDAY, userBean.getUser().getBirthday());
                        ForPreference.putString(ForContents.USER_ADDRESS, userBean.getUser().getAddress());
                        ForPreference.putString(ForContents.USER_PHONE, name);
                        ForPreference.putString(ForContents.USER_DESCRIBE, userBean.getUser().getDescribe());

                        Intent mIntent;
                        if (ForPreference.getInt(ForContents.USER_COUNT) <= 0) {
                            //跳转添加娃
                            ForToast.showToast(R.string.fist_wa_null);
                            mIntent = new Intent(LoginActivity.this, AddWaActivity.class);
                        } else {
                            //跳转主页面
                            mIntent = new Intent(LoginActivity.this, MainActivity.class);
                        }
                        startActivity(mIntent);
                        MyApplication.getInstance().closeActivity(LoginActivity.this);
                    } else {
                        hideLoading();
                        ForToast.showToast(jsonObject.getString(HttpKey.MESSAGE));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

//    private BroadcastReceiver smsReceiver;
//    private IntentFilter filter;
//    private String patternCoder = "(?<!\\d)\\d{6}(?!\\d)";
//
//    public void getIntercept(){
//        filter = new IntentFilter();
//        //设置短信拦截参数
//        filter.addAction("android.provider.Telephony.SMS_RECEIVED");
//        filter.setPriority(Integer.MAX_VALUE);
//        smsReceiver = new BroadcastReceiver() {
//            @Override
//            public void onReceive(Context context, Intent intent) {
//                this.abortBroadcast();
//                Object[] objs = (Object[]) intent.getExtras().get("pdus");
//                for (Object obj : objs) {
//                    byte[] pdu = (byte[]) obj;
//                    SmsMessage sms = SmsMessage.createFromPdu(pdu);
//                    String message = sms.getMessageBody();
//                    Log.d("短信内容", "message：" + message);
//                    // 短息的手机号。。+86开头？
//                    String from = sms.getOriginatingAddress();
//                    Log.d("短信来源", "from ：" + from);
//                    if (!TextUtils.isEmpty(from)) {
//                        String code = patternCode(message);
//                        if (!TextUtils.isEmpty(code)) {
//                            Message msg=new Message();
//                            msg.what= 1;
//                            Bundle bundle=new Bundle();
//                            bundle.putString("messagecode", code);
//                            msg.setData(bundle);
//                            hander.sendMessage(msg);
//                        }
//                    }
//                }
//            }
//        };
//        registerReceiver(smsReceiver, filter);
//    }
//
//    private String patternCode(String patternContent) {
//        if (TextUtils.isEmpty(patternContent)) {
//            return null;
//        }
//        Pattern p = Pattern.compile(patternCoder);
//        Matcher matcher = p.matcher(patternContent);
//        if (matcher.find()) {
//            return matcher.group();
//        }
//        return null;
//    }

}
